package com.example.tetris;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.dataability.DataAbilityUtils;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;
import ohos.utils.PacMap;

import java.io.FileDescriptor;

public class SQLite extends Ability {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");

    // 数据库操作类RdbStore
    private RdbStore rdbStore;
    // 表名称
    private final String TABLENAME_CLASSIC = "game_recording_classic";
    // 访问DataAbility的唯一路径
    private Uri uri;
    // DataAbility数据操作类
    private DataAbilityHelper helper;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        HiLog.info(LABEL_LOG, "SQLite onStart");

        helper = DataAbilityHelper.creator(this);
        uri = Uri.parse("dataability:///com.example.tetris.SQLite");

        initDatabase(this);

    }

    // 初始化数据库
    private void initDatabase(Context context){
        //1.指定数据库文件路径
        StoreConfig config = StoreConfig.newDefaultConfig("game_recording.sqlite");
        HiLog.info(LABEL_LOG, String.valueOf(context.getDatabaseDir()));
        //2.定义用于创建和升级表的回调对象
        RdbOpenCallback callback = new RdbOpenCallback() {
            @Override
            public void onCreate(RdbStore rdbStore) {
                rdbStore.executeSql("create table if not exists " + TABLENAME_CLASSIC + "(id integer primary key autoincrement, date text not null, score integer not null,seconds text not null)");
            }
            @Override
            public void onUpgrade(RdbStore rdbStore, int i, int i1) {

            }
        };
        //创建数据库助手对象
        DatabaseHelper helper = new DatabaseHelper(context);
        //获取数据库对象，通过该对象对数据库中的表进行增删改查
        rdbStore = helper.getRdbStore(config, 1, callback);
        //到这一步为止，系统会在本应用的安装目录下创建一个sqlite文件（game_recording.sqlite），包含两张表
    }




    @Override
    public ResultSet query(Uri uri, String[] columns, DataAbilityPredicates predicates)

    {
        RdbPredicates rdbPredicates = DataAbilityUtils.createRdbPredicates(predicates, TABLENAME_CLASSIC);
        return rdbStore.query(rdbPredicates, columns);
    }

    @Override
    public int insert(Uri uri, ValuesBucket value) {
        long res = rdbStore.insert(TABLENAME_CLASSIC, value);
        return (int)res;
    }

    // 删除数据
    @Override
    public int delete(Uri uri, DataAbilityPredicates predicates) {
        RdbPredicates rdbPredicates = DataAbilityUtils.createRdbPredicates(predicates, TABLENAME_CLASSIC);
        return rdbStore.delete(rdbPredicates);
    }

}